import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { ListView, Card, WhiteSpace, SearchBar } from "antd-mobile";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import { Row, Col, Spin, } from "antd";
import moment from "moment";
import './index.less';
import { request, setMainFormTitle, setMainFormBack } from "src/business/util_tool";
// const Item = List.Item;
// const Brief = Item.Brief;

function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}

/**
 * 组件：新闻列表状态
 */
export interface NewsListViewState extends BaseReactElementState {
    /** 长列表数据 */
    dataSource?: any;
    /** 请求的数据 */
    list?: any[];
    /** 上拉加载 */
    upLoading?: boolean;
    /** 下拉刷新 */
    pullLoading?: boolean;
    /** 长列表容器高度 */
    height?: any;
    /** 当前第几页 */
    page: number;
    /** 记录tab状态 */
    tab_status?: string;
    empty?: boolean;
    animating?: any;
    // 每页数量
    pageCount: number;

    keyword?: string;
}

/**
 * 组件：新闻列表
 * 新闻列表
 */
export class NewsListView extends BaseReactElement<NewsListViewControl, NewsListViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            list: [],
            upLoading: false,
            pullLoading: false,
            height: document.documentElement!.clientHeight,
            page: 1,
            tab_status: 'participate',
            empty: false,
            animating: true,
            pageCount: 10,
            keyword: '',
        };
    }
    componentDidMount() {
        this.getNewsList();
    }
    onClickRow = (id: string) => {
        this.props.history!.push(ROUTE_PATH.newsInfo + '/' + id);
    }
    getNewsList(param: any = {}, page: number = 1) {
        let { list, pageCount, keyword } = this.state;
        if (this.props.match!.params.key) {
            param['organization_id'] = this.props.match!.params.key;
        }
        // param['all'] = true;
        if (keyword !== '') {
            param['title'] = keyword;
        }
        this.setState(
            {
                animating: true,
            },
            () => {
                request(this, AppServiceUtility.article_list_service.get_news_list!(param, page, pageCount)!
                    .then((data: any) => {
                        if (data && data.result.length > 0) {
                            this.setState({
                                list: list!.concat(data.result),
                                page,
                                animating: false,
                            });
                        } else {
                            this.setState({
                                animating: false,
                                empty: true,
                            });
                        }
                    })).catch((err) => {
                        console.info(err);
                    });
            }
        );
    }
    /** 下拉事件 */
    onEndReached = () => {
        const { animating, page } = this.state;
        if (animating === true) {
            return;
        }
        this.getNewsList({}, page + 1);
    }
    searchKey(e: any) {
        this.setState(
            {
                empty: false,
                keyword: e,
                list: [],
            },
            () => {
                this.getNewsList({});
            }
        );
    }
    render() {
        setMainFormTitle('南海区智慧康养');
        setMainFormBack('', () => {
            this.props.history!.push(ROUTE_PATH.home);
        });
        const { list, dataSource, animating, empty } = this.state;
        const renderRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <Card className='list-conten'>
                    <Row type='flex' justify='center' onClick={this.onClickRow.bind(this, owData.id)}>
                        <Col className='list-col' span={10}><img src={owData.hasOwnProperty('app_img_list') && owData.app_img_list.length > 0 ? owData.app_img_list[0] : 'https://www.e-health100.com/api/attachment/activityphoto/8336'} style={{ height: '72pt', width: '110pt' }} /></Col>
                        <Col span={14} className='list-col'>
                            <Row className="maxLine2" style={{ WebkitBoxOrient: 'vertical' }}><strong>{owData.title}</strong></Row>
                            <Row>作者：{owData['author'] || ''}</Row>
                            <Row className='list-t'>{moment(owData.create_date).format("YYYY-MM-DD hh:mm")}</Row>
                        </Col>
                    </Row>
                </Card>
            );
        };
        return (
            <Row>
                <SearchBar placeholder="搜索" maxLength={8} onSubmit={(e: any) => this.searchKey(e)} />
                <Row className='tabs-content'>
                    {
                        list && list.length ?
                            <ListView
                                ref={el => this['lv'] = el}
                                dataSource={dataSource.cloneWithRows(list)}
                                renderRow={renderRow}
                                initialListSize={10}
                                pageSize={10}
                                renderBodyComponent={() => <MyBody />}
                                style={{ height: this.state.height }}
                                onEndReached={this.onEndReached}
                            />
                            :
                            null
                    }
                    {animating ? <Row>
                        <WhiteSpace size="lg" />
                        <Row style={{ textAlign: 'center' }}>
                            <Spin size="large" />
                        </Row>
                        <WhiteSpace size="lg" />
                    </Row> : null}
                    {empty ? <Row>
                        <WhiteSpace size="lg" />
                        <Row className='tabs-content' type='flex' justify='center'>{list && list.length ? '已经是最后一条了' : '无数据'}</Row>
                        <WhiteSpace size="lg" />
                    </Row> : null}
                </Row>
            </Row>
        );
    }
}

/**
 * 控件：新闻列表控制器
 * 新闻列表
 */
@addon('NewsListView', '新闻列表', '新闻列表')
@reactControl(NewsListView, true)
export class NewsListViewControl extends BaseReactElementControl {
    constructor() {
        super();
    }
}